import { DownOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Dropdown, Menu, message } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm, { FormValueType } from './components/UpdateForm';
import { ConfigListItem } from './data';
import { queryRule, updateRule, addRule, removeRule } from './service';
import moment from 'moment';
import { Dispatch } from 'redux';
import { bdExec } from '@/helpers/RequestHelper';
import * as tsxHelper from '@/helpers/TsxHelper';

interface ConfigListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
}

/**
 * 添加节点
 */
const handleAdd = async (fields: FormValueType) => {
  return bdExec({fn: addRule, args: fields, successMsg: '添加成功',failMsg: '添加失败请重试！'});
};

/**
 * 更新节点
 */
const handleUpdate = async (fields: FormValueType) => {
  return bdExec({fn: updateRule, args: fields, successMsg: '更新成功',failMsg: '更新失败请重试！'});
};

/**
 *  删除节点
 */
const handleRemove = async (selectedRows: ConfigListItem[]) => {
  if (!selectedRows) return true;
  const ids:any = selectedRows.map(row => row.id).toString();
  return bdExec({fn: removeRule, args: {ids}, successMsg: '删除成功，即将刷新',failMsg: '删除失败，请重试！', hasLoading: false});
};

const ConfigGroupList: React.FC<ConfigListProps> = (props) => {

  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const [rowKeys, setRowKeys] = useState<string[]|number[]>([]);
  const [stateData, setStateData] = useState<any>({data: {}});
  const actionRef = useRef<ActionType>();
  
  const columns:ProColumns<ConfigListItem>[] = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '类型',
      dataIndex: 'type',
      hideInSearch: true,
    },
    {
      title: '变量标示',
      dataIndex: 'nickname',
      // hideInSearch: true,
    },
    {
      title: '描述',
      dataIndex: 'remark',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      sorter: true,
      hideInSearch: true,
      render: (val:any) => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_: any, record: React.SetStateAction<{}>) => (
        <>
          <a
            onClick={() => {
              handleUpdateModalVisible(true);
              setStepFormValues(record);
            }}
          >
            编辑
          </a>
        </>
      ),
    },
  ];

  const getListData = (params:any) => {
    return queryRule(params).then((res:any) => {
      if(res.code === 0){
        setStateData(res)
        return res.data.listData;
      }else{
        message.error(res.msg);
      }
    })
  }


  return (
    <PageHeaderWrapper>
      
      <ProTable<ConfigListItem>
        headerTitle=""
        actionRef={actionRef}
        rowKey="key"
        pagination={{
          showSizeChanger: true,
        }}
        toolBarRender={(action, { selectedRows }) => [
          <Button icon={'plus'} type="primary" onClick={() => handleModalVisible(true)}>
            新建
          </Button>,
          selectedRows && selectedRows.length > 0 && (
            <Dropdown
              overlay={
                <Menu
                  onClick={async e => {
                    if (e.key === 'remove') {
                      tsxHelper.showDeleteConfirm(
                        'danger',
                        handleRemove,
                        selectedRows, 
                        () => {
                          setRowKeys([]);
                          action.reload();
                        }
                      )
                    }
                  }}
                  selectedKeys={[]}
                >
                  <Menu.Item key="remove">批量删除</Menu.Item>
                </Menu>
              }
            >
              <Button>
                批量操作 <DownOutlined />
              </Button>
            </Dropdown>
          ),
        ]}
        tableAlertRender={(selectedRowKeys, selectedRows) => (
          <div>
            已选择 <a style={{ fontWeight: 600 }}>{selectedRowKeys.length}</a> 项&nbsp;&nbsp;
            {/* <span>
              服务调用次数总计 {selectedRows.reduce((pre, item) => pre + item.callNo, 0)} 万
            </span> */}
          </div>
        )}
        request={(params) => getListData(params)}
        columns={columns}
        rowSelection={{
          onChange: (selectedRowKeys, selectedRows) => {
            setRowKeys(selectedRowKeys);
          },
          selectedRowKeys: rowKeys,
        }}
      />
      
      <CreateForm
        onSubmit={async (value) => {
          const success:any = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        otherValues={{
          common: stateData.data.common || {},
        }}
      />
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <UpdateForm
          onSubmit={async value => {
            const success = await handleUpdate(value);
            if (success) {
              handleModalVisible(false);
              setStepFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => handleUpdateModalVisible(false)}
          updateModalVisible={updateModalVisible}
          values={stepFormValues}
          otherValues={{
            common: stateData.data?.common || {},
          }}
        />
      ) : null}
    </PageHeaderWrapper>
  );
};

export default Form.create<ConfigListProps>()(ConfigGroupList);
